<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加分类按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAdd">添加分类</el-button>
        </el-col>
      </el-row>

      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="序号"
        border
        :show-row-hover="false"
        class="treetable"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            type="success"
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt">
          <el-button type="primary" icon="el-icon-edit" size="mini"
            >编辑</el-button
          >
          <el-button type="danger" icon="el-icon-delete" size="mini"
            >删除</el-button
          >
        </template>
      </tree-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="isAddShow"
      width="50%"
      @close="addCateDialogClosed"
    >
      <!-- 添加分类的表单 -->
      <el-form
        :model="addModel"
        :rules="addRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addModel.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <!-- options 用来指定数据源 -->
          <!-- props 用来指定配置对象 -->
          <el-cascader
            expand-trigger="hover"
            :options="parentCateList"
            :props="cascaderProps"
            v-model="selectedKeys"
            @change="parentCateChanged"
            clearable
            change-on-select
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddShow = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      queryData: {
        query: 3,
        pagenum: 1,
        pagesize: 5,
      },
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        { label: '是否有效', prop: '', type: 'template', template: 'isok' },
        { label: '排序', prop: '', type: 'template', template: 'order' },
        { label: '操作', prop: '', type: 'template', template: 'opt' },
      ],
      total: 0,
      isAddShow: false,
      addModel: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0,
      },
      addRules: {
        cat_name: [
          {
            required: true,
            message: '请输入分类名哦',
            trigger: 'blur',
          },
        ],
      },
      parentCateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
      },
      // 选中的父级分类的Id数组
      selectedKeys: [],
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$axios({
        method: 'get',
        url: 'categories',
        params: this.queryData,
      })

      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.cateList = res.data.result
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryData.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(newPage) {
      this.queryData.pagenum = newPage
      this.getCateList()
    },
    showAdd() {
      this.isAddShow = true
      this.getParentCates()
    },
    async getParentCates() {
      const { data: res } = await this.$axios({
        method: 'get',
        url: 'categories',
        params: { type: 2 },
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
    //   console.log(res.data)
      this.parentCateList = res.data
    },
    // 选择项发生变化触发这个函数
    parentCateChanged() {
      // 如果 selectedKeys 数组中的 length 大于0，证明选中的父级分类
      // 反之，就说明没有选中任何父级分类
        if (this.selectedKeys.length > 0) {
          // 父级分类的Id
          this.addModel.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
          // 为当前分类的等级赋值
          this.addModel.cat_level = this.selectedKeys.length
          return
        } else {
          // 父级分类的Id
          this.addModel.cat_pid = 0
          // 为当前分类的等级赋值
          this.addModel.cat_level = 0
        }
    //   this.Model.cat_level = this.addModel.cat_pid.length
    //   this.addModel.cat_pid =
    //     this.addModel.cat_pid[this.Model.cat_pid.length - 1]
    },
    // 点击按钮，添加新的分类
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$axios.post(
          'categories',
          this.addModel
        )

        if (res.meta.status !== 201) {
          return this.$msg.error(res.meta.msg)
        }

        this.$msg.success(res.meta.msg)
        this.getCateList()
        this.isAddShow = false
      })
    },
    // 监听对话框的关闭事件，重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addModel.cat_level = 0
      this.addModel.cat_pid = 0
    },
  },
  created() {
    this.getCateList()
  },
}
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}

.el-cascader {
  width: 80%;
}
</style>
